package com.yesorno.activity;

import org.json.JSONException;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.yesorno.constants.Constants;
import com.yesorno.model.HttpResponseObject;
import com.yesorno.model.MyTimerTask;
import com.yesorno.ui.CustomTitleActivity;
import com.yesorno.utils.HttpUtils;

/**
 * 登录即首页的activity
 * 
 * @author samoin
 * @date 2011-07-05
 * @version 0.1
 * 
 */
public class LoginActivity extends CustomTitleActivity {
	private Button loginBtn;
	private Button regBtn;
	private Button findPwdBack;
	private EditText passport;
	private EditText password;

	LoginBtnsClickListeners lbc;
	ProgressDialog progressDialog;

	/**
	 * 给title里追加按钮等组件
	 */
	@Override
	public void setTitleViews() {
		LinearLayout titleLayout = getTITLE_LAYOUT();
		findPwdBack = CustomTitleActivity.createTitleLeftButton(
				LoginActivity.this, R.string.login_title_btn_findpwd,
				Constants.TITLE_BTN_MARGIN1);
		findPwdBack.setOnClickListener(lbc);
		titleLayout.addView((View) findPwdBack.getParent());
		titleLayout
				.addView((View) CustomTitleActivity.createTitleDesc(
						LoginActivity.this, R.string.login_title_common, 0)
						.getParent());
		titleLayout.addView((View) CustomTitleActivity.createTitleDesc(
				LoginActivity.this, 0, 0).getParent());
	}

	/**
	 * 设置布局对应的id
	 */
	@Override
	public void setLayoutId() {
		setContentView(R.layout.main);
	}

	/**
	 * 监听，按后退键以后，退出程序
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK，同时没有重复

			// Ask the user if they want to quit
			new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle(R.string.toast_loginout_title)
					.setMessage(R.string.toast_loginout_info)
					.setPositiveButton(R.string.toast_loginout_yes,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// Stop the activity
									// LoginActivity.this.finish();
									Intent home = new Intent(Intent.ACTION_MAIN);
									home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
									home.addCategory(Intent.CATEGORY_HOME);
									startActivity(home);
								}
							})
					.setNegativeButton(R.string.toast_loginout_no, null).show();
			return true;
		}
		return super.onKeyDown(keyCode, event);

	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyTimerTask.removeMyTask();
		lbc = new LoginBtnsClickListeners();
		setAllView();
		addBtnClickListeners();
		// System.out.println("create thread -> "
		// + Thread.currentThread().getName());
		progressDialog = new ProgressDialog(LoginActivity.this);
		progressDialog.setTitle(R.string.dialog_logining);
		// playRing();
		// vibrator();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		AlertService.timer.cancel();
		AlertService.timer = null;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			/* 取得来自Activity2的数据，并显示于画面上 */
			// System.out.println(data.getStringExtra("test"));
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 添加所有的按钮的点击事件
	 */
	private void addBtnClickListeners() {
		loginBtn.setOnClickListener(lbc);
		regBtn.setOnClickListener(lbc);
		findPwdBack.setOnClickListener(lbc);
	}

	public void showDialog() {
		// System.out
		// .println("show thread -> " + Thread.currentThread().getName());
		progressDialog.show();
	}

	public void hideDialog() {
		if (progressDialog != null) {
			// System.out.println("hide thread -> "
			// + Thread.currentThread().getName());
			progressDialog.hide();
		}
	}

	/**
	 * 登录页面按钮的监听类
	 * 
	 * @author samoin
	 * @date 2011-07-06
	 * @version 0.1
	 * 
	 */
	class LoginBtnsClickListeners implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (v == loginBtn) {
				login();
			}
			if (v == regBtn) {
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, RegistActivity.class);
				// startActivity(intent);
				startActivityForResult(intent, 0);
			}
			if (v == findPwdBack) {
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, FindPwdActivity.class);
				// startActivity(intent);
				startActivityForResult(intent, 0);
			}
		}

		private void login() {
			String pass = passport.getText().toString();
			String pwd = password.getText().toString();
			HandlerThread handlerThread = new HandlerThread("loginThread");
			handlerThread.start();
			LoginHandler handler = new LoginHandler(handlerThread.getLooper());
			// System.out.println("login - >:" +
			// Thread.currentThread().getName());
			showDialog();
			Message msg = handler.obtainMessage();
			Bundle b = new Bundle();
			b.putString("pass", pass);
			b.putString("pwd", pwd);
			msg.setData(b);
			msg.sendToTarget();
		}
	}

	class MyHandler extends Handler {
		public MyHandler() {
			super();
		}

		public MyHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			// System.out.println("MyHandler thread -> "
			// + Thread.currentThread().getName());
			Bundle bundle = msg.getData();
			if (msg.arg1 == 0) {
				Toast.makeText(LoginActivity.this, R.string.toast_login_ok,
						1000).show();
			} else {
				Toast.makeText(LoginActivity.this,
						bundle.getString("errorInfo"), 1000).show();
			}
			hideDialog();
			super.handleMessage(msg);
		}

	}

	class LoginHandler extends Handler {
		public LoginHandler() {

		}

		public LoginHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			// System.out
			// .println("handle - >:" + Thread.currentThread().getName());
			Bundle b = msg.getData();
			String pass = b.getString("pass");
			String pwd = b.getString("pwd");
			HttpResponseObject hro = HttpUtils.getInfoByUrlPost(
					Constants.USER_LOGIN_URL + "pass=" + pass + "&pwd=" + pwd,
					LoginActivity.this);
			// JSONObject map = hro.getResult();
			// TODO 登录的验证
			MyHandler myHandler = new MyHandler(Looper.getMainLooper());
			Message msg2 = myHandler.obtainMessage();
			if (hro.getCode() != 0) {
				msg2.arg1 = hro.getCode();
				Bundle bundle = new Bundle();
				bundle.putString("errorInfo", hro.getMessages());
				msg2.setData(bundle);
			} else {
				Constants.USER_PASS = pass;
				Constants.USER_PWD = pwd;
				try {
					Constants.USER_ID = hro.getResult().getLong("userId");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, HallActivity.class);
				startActivityForResult(intent, 0);
			}
			msg2.sendToTarget();
			super.handleMessage(msg);
		}

	}

	/**
	 * 获取所有的View
	 */
	private void setAllView() {
		loginBtn = (Button) findViewById(R.id.login_login);
		regBtn = (Button) findViewById(R.id.login_regist);
		passport = (EditText) findViewById(R.id.login_pass);
		password = (EditText) findViewById(R.id.login_pwd);
		loginBtn.getPaint().setFakeBoldText(true);// 设置粗体
		regBtn.getPaint().setFakeBoldText(true);
	}

}